<template>
    <div class="msg">
        <div class="item">
            <div class="icon" style="background: #0066CC;"></div>
            <div class="label">水厂</div>
            <el-checkbox v-model="checkboxForm.shuiChang" size="large"
                @change="tagetCheckbox($event, 'shuiChang', '#0066CC')" />
        </div>
        <div class="item">
            <div class="icon" style="background: #1E90FF;"></div>
            <div class="label">预留口</div>
            <el-checkbox v-model="checkboxForm.shuiBiao" size="large"
                @change="tagetCheckbox($event, 'shuiBiao', '#1E90FF')" />
        </div>
        <div class="item">
            <div class="icon" style="background: #32CD32;"></div>
            <div class="label">排气阀井</div>
            <el-checkbox v-model="checkboxForm.paiQiJing" size="large"
                @change="tagetCheckbox($event, 'paiQiJing', '#32CD32')" />
        </div>
        <div class="item">
            <div class="icon" style="background: #8B4513;"></div>
            <div class="label">排泥阀井</div>
            <el-checkbox v-model="checkboxForm.paiNiJing" size="large"
                @change="tagetCheckbox($event, 'paiNiJing', '#8B4513')" />
        </div>
        <div class="item">
            <div class="icon" style="background: #FFD700;"></div>
            <div class="label">阀门井</div>
            <el-checkbox v-model="checkboxForm.faMenJing" size="large"
                @change="tagetCheckbox($event, 'faMenJing', '#FFD700')" />
        </div>
        <div class="item">
            <div class="icon" style="background: #FF0000;"></div>
            <div class="label">消防栓</div>
            <el-checkbox v-model="checkboxForm.xiaoFangShuan" size="large"
                @change="tagetCheckbox($event, 'xiaoFangShuan', '#FF0000')" />
        </div>
        <div class="item">
            <div class="icon" style="background: #428cec;"></div>
            <div class="label">流量计</div>
            <el-checkbox v-model="checkboxForm.flowMeter" size="large"
                @change="tagetCheckbox($event, 'flowMeter', '#428cec')" />
        </div>
    </div>
    <div id="cesiumContainer" ref="cesiumContainer">
        <newPopup v-if="popupVisible" :dataEntity="dataEntity" :style="popupStyle" class="popup"
            @closePopup="closePopup" />
    </div>
</template>

<script setup name="Dispatch-cockpit">
import * as Cesium from 'cesium';
import newPopup from './newPopup.vue'
import { onMounted, nextTick, ref, defineEmits } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { AMapImageryProvider, BaiduImageryProvider, GeoVisImageryProvider, TdtImageryProvider } from '@cesium-china/cesium-map'
import { getPipelineRetworkMonitoringList, getPipelineRetworkMonitoringWaterMeterList, getPipelineRetworkMonitoringValveList } from '@/api/dispatch/detection/cockpit';
Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI2MzlmOGQxZi05M2UwLTQ3NzItYTlhNS03N2NkMDgxYzMyMjkiLCJpZCI6MTg4NDY1LCJpYXQiOjE3MzkyMDMyOTR9.a6XM6flLYaqGnrIfPfCu8BWE7TSeI8ps-C1A_2wlvqc';

const emit = defineEmits(['onload']);
const popupStyle = ref({ top: '0px', left: '0px' });

const cesiumContainer = ref(null);
let viewer = null;
let pipelineArray = ref([]);
let pointArray = ref([]);
let lastClickCartesian = null; // 点击获取到的经纬度
const popupVisible = ref(false);
let dataEntity = ref([]);
const route = useRoute();
const router = useRouter();

const checkboxForm = ref({
    shuiChang: true,
    shuiBiao: true,
    paiQiJing: true,
    paiNiJing: true,
    faMenJing: true,
    xiaoFangShuan: true,
    flowMeter: true
});

const tagetCheckbox = (event, name, color) => {
    pointArray.value.forEach((item) => {
        if (item.labelOptions.color == color) {
            item.show = event;
        }
    })
    checkboxForm.value[name] = event;
}


// 更新大小
import { SceneTransforms } from 'cesium';

const closePopup = () => {
    popupVisible.value = false;
};
const updatePopupPosition = () => {
    if (!viewer || !lastClickCartesian || !popupVisible.value) return;

    // 1) 先拿“窗口坐标”（相对 canvas 的像素坐标）
    const winPos = SceneTransforms.wgs84ToWindowCoordinates(
        viewer.scene,
        lastClickCartesian
    );
    if (!winPos) return;

    // 2) 再减去容器的页面偏移，让 left/top 变成“相对于容器”
    const rect = cesiumContainer.value.getBoundingClientRect();

    // 如果 .popup 的 offsetParent 是 .app-container（position:relative），
    // 那就再减去 .app-container 的 rect；否则只减容器 rect。
    const app = document.querySelector('.app-container');
    const appRect = app?.getBoundingClientRect?.() || { left: 0, top: 0 };

    // 这里假设 .popup 的绝对定位参照是 .app-container：
    const left = winPos.x + rect.left - appRect.left;
    const top = winPos.y + rect.top - appRect.top;

    popupStyle.value = {
        left: `${left}px`,
        top: `${top}px`,
    };
};

function computePolygonCentroid(positionsArray) {
    // 将经纬度转换为笛卡尔坐标
    const cartesians = Cesium.Cartesian3.fromDegreesArray(positionsArray);

    // 方法1：简单算术平均（适用于凸多边形）
    const centroid = new Cesium.Cartesian3();
    cartesians.forEach(pos => Cesium.Cartesian3.add(centroid, pos, centroid));
    Cesium.Cartesian3.divideByScalar(centroid, cartesians.length, centroid);

    // 方法2：使用Cesium内置方法（适用于任何多边形）
    const boundingSphere = Cesium.BoundingSphere.fromPoints(cartesians);
    return boundingSphere.center;
}
let colorAndName = {
    'sc': '水厂',
    'sb': '水表',
    '1': "排水阀井",
    '2': "排泥阀井",
    '3': "阀门井",
    '4': "消防栓",
    '5': "流量计",
}
// 生成线条函数
function generatePolylines(options) {
    const { linePosition } = options;
    let positionsArray = [];
    linePosition.split("|").forEach((position) => {
        const [lat, lon] = position.split(",");
        positionsArray.push(...[+lon, +lat]);
    });

    const center = computePolygonCentroid(positionsArray);

    const entity = viewer.entities.add({
        name: '随机线',
        polyline: {
            positions: Cesium.Cartesian3.fromDegreesArray(positionsArray),
            width: 10,
            material: new Cesium.PolylineGlowMaterialProperty({
                glowPower: 0.2,
                color: Cesium.Color.fromRandom({ alpha: 1 }),
            }),
            clampToGround: true,
        },
    });
    entity.polylineOptions = options;
    entity.polylineCenter = center;

    pipelineArray.value.push(entity);
}
const createLabel = (options, color) => {
    const { meterName, geoPosition, wellType } = options;

    // 检查名称是否有效
    if (typeof meterName !== 'string' || !meterName.trim()) {
        console.warn('无效的meterName:', meterName);
        return;
    }
    // 转换为WGS84
    const [lat, lon] = geoPosition.split(",");
    const entity = viewer.entities.add({
        position: Cesium.Cartesian3.fromDegrees(+lon, +lat, 1),
        point: {
            pixelSize: 8,
            color: Cesium.Color.fromCssColorString(color || "#ff0000"),
            outlineColor: Cesium.Color.WHITE,
            outlineWidth: 2,
            heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,

        },
        // label: {
        //     text:meterName,
        //     font: "bold 16px sans-serif",
        //     style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        //     fillColor: Cesium.Color.WHITE,
        //     outlineColor: Cesium.Color.BLACK,
        //     heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
        //     verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        //     pixelOffset: new Cesium.Cartesian2(0, -20)
        // }
    });

    entity.labelOptions = options;
    entity.labelOptions.color = color;
    entity.labelOptions.typeAndName = colorAndName[wellType];

    pointArray.value.push(entity);
}

const getCorrectPosition = async (entity, center) => {
    const position = center || entity.position?.getValue(viewer.clock.currentTime);

    const cartographic = Cesium.Cartographic.fromCartesian(position);

    // 获取该点的实际地形高度
    const terrainHeight = await viewer.scene.globe.getHeight(cartographic);

    // 计算正确坐标
    return {
        longitude: Cesium.Math.toDegrees(cartographic.longitude),
        latitude: Cesium.Math.toDegrees(cartographic.latitude),
        actualHeight: terrainHeight + cartographic.height // 地形高度 + 你的设置值
    };
};

async function flyToPosition(cartesian, options = {}) {
    // 默认参数合并
    const defaults = {
        pitch: -45,      // 默认俯仰角
        range: 2000,     // 默认观察距离(米)
        duration: 1,   // 默认动画时长
        flyOver: true    // 是否飞越目标点
    };
    const config = { ...defaults, ...options, pitch: -45 };

    try {
        // 1. 获取精确地形高度
        const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        const terrainSample = await Cesium.sampleTerrainMostDetailed(
            viewer.terrainProvider,
            [cartographic]
        );
        const terrainHeight = terrainSample[0].height;
        // 2. 创建带高度的包围球
        const boundingSphere = new Cesium.BoundingSphere(
            Cesium.Cartesian3.fromRadians(
                cartographic.longitude,
                cartographic.latitude,
                terrainHeight  // 1米安全高度
            ),
            50 // 包围球半径(米)
        );

        // 3. 执行飞行
        await viewer.camera.flyToBoundingSphere(boundingSphere, {
            offset: new Cesium.HeadingPitchRange(
                0, // 朝向正北
                Cesium.Math.toRadians(config.pitch),
                config.range * 4
            ),
            duration: config.duration,
            // flyOverLongitude: config.flyOver ? cartographic.longitude : undefined,
            // maximumHeight: terrainHeight + config.range * 2, // 飞行最高点
            easingFunction: Cesium.EasingFunction.QUINTIC_IN_OUT, // 更平滑的缓动函数
        });

    } catch (error) {
        console.log('飞行错误');
    }
}

const setInputAction = () => {
    // 点击事件处理修改
    viewer.screenSpaceEventHandler.setInputAction(async function (click) {
        const pickedObject = viewer.scene.pick(click.position);
        if (Cesium.defined(pickedObject)) {
            const entity = pickedObject.id;
            if (entity.point) {

                const correctPos = await getCorrectPosition(pickedObject.id);

                // 获取地形经纬度
                lastClickCartesian = Cesium.Cartesian3.fromDegrees(
                    correctPos.longitude,
                    correctPos.latitude,
                    correctPos.actualHeight
                )
                dataEntity.value = entity.labelOptions;
                if (lastClickCartesian) {
                    popupVisible.value = true;
                }

                flyToPosition(lastClickCartesian)
            }
            if (entity.label) {
                if (entity.label.text == '石带水厂') {
                    ElMessageBox.confirm('是否跳转水厂？', '系统提示', { confirmButtonText: '是', cancelButtonText: '否' }).then(() => {
                        router.push({
                            path: '/',
                        })
                    })
                }
            }
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    viewer.screenSpaceEventHandler.setInputAction(async function (movement) {
        const pickedObject = viewer.scene.pick(movement.endPosition);
        if (Cesium.defined(pickedObject) && pickedObject.id && pickedObject.id.point) {
            // 如果移入的是 point 实体
            viewer.scene.canvas.style.cursor = "pointer";
        } else {
            // 恢复默认
            viewer.scene.canvas.style.cursor = "default";
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
};
const resize = () => {
    const rect = cesiumContainer.value.getBoundingClientRect()
    cesiumContainer.value.style.width = `calc(100vw - ${rect.left}px)`;
    cesiumContainer.value.style.height = `calc(100vh - ${rect.top}px)`;
    viewer.resize();
}
onMounted(async () => {
    viewer = new Cesium.Viewer('cesiumContainer', {
        timeline: false,
        animation: false,
        geocoder: false,
        homeButton: false,
        sceneModePicker: false,
        navigationHelpButton: false,
        fullscreenButton: false,
        baseLayerPicker: false,   // 禁用底图选择器
        terrain: Cesium.Terrain.fromWorldTerrain({
            requestWaterMask: true,
        }),
        useBrowserRecommendedResolution: false, // 不要降分辨率
    });
    // 禁用双击锁定
    viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

    createLabel({ meterName: '石带水厂', geoPosition: '18.750000017544195,109.73175633500372', wellType: 'sc' }, '#0066CC');

    viewer.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(109.73175633500372, 18.560000017544195, 15000), // 经度, 纬度, 高度（米）
        orientation: {
            heading: Cesium.Math.toRadians(0),   // 朝向（0=正北，90=正东）
            pitch: Cesium.Math.toRadians(-45),   // 俯视角（-90=垂直向下）
            roll: 0.0                            // 横滚角（通常为0）
        }
    });
    // // 加载海南省地形数据
    // viewer.terrainProvider = new Cesium.CesiumTerrainProvider({
    //     url: '/terrainProvider/value/',
    //     requestVertexNormals: true
    // })
    viewer.scene.postRender.addEventListener(updatePopupPosition);

    // 调用管网数据接口
    getPipelineRetworkMonitoringList().then(({ data }) => {
        data.forEach(item => {
            generatePolylines({ ...item, wellType: 'sb' });
        })
    })
    // 调用水表数据接口
    getPipelineRetworkMonitoringWaterMeterList().then(({ data }) => {
        data.forEach(item => {
            createLabel(item, '#1E90FF');
        })
    })

    // 获取井信息 
    getPipelineRetworkMonitoringValveList().then(({ data }) => {
        console.log(data);
        data.forEach(item => {
            createLabel({ ...item, meterName: item.wellName }, ['', '#8B4513', '#32CD32', '#FFD700', '#FF0000','#428cec'][item.wellType]);
        })

    })
    setInputAction();
    let helper = new Cesium.EventHelper();
    const RemoveCallback = helper.add(viewer.scene.globe.tileLoadProgressEvent, async function (event) {
        if (event == 0) {
            emit('onload');

            // const osmBuildings = await Cesium.Cesium3DTileset.fromIonAssetId(96188);
            // viewer.scene.primitives.add(osmBuildings);
            // 删除事件监听
            RemoveCallback()
        }
    })
    resize();
    window.addEventListener('resize', resize);
});


</script>

<style scoped lang="scss">
.app-container {
    padding: 0 !important;
    overflow: hidden;
    position: relative;
}

.cesium-map {
    position: relative;
}

#cesiumContainer {
    position: relative;
    width: 100%;
    height: 100%;
}

:deep(.cesium-viewer-bottom) {
    display: none;
}

.popup {
    position: absolute;
    z-index: 9999;
}

.msg {
    position: absolute;
    top: 130px;
    right: 380px;
    width: 200px;
    z-index: 9999;

    .item {
        display: flex;
        margin-bottom: 8px;
        align-items: center;
        height: 15px;

        .icon {
            width: 15px;
            height: 15px;
            border-radius: 10px;
        }

        .label {
            margin-left: 10px;
            font-size: 14px;
            color: #fff;
            height: 10px;
            line-height: 10px;
        }
    }
}

.el-checkbox {
    margin-left: 10px;
    margin-bottom: 0px !important;
}

.popup-icon {
    position: absolute;
    z-index: 9999;
}
</style>